package com.jnxx.task.tools;

import com.jnxx.basic.util.GetStaffRequestUtil;
import com.jnxx.task.WxUtils.TokenUtils;
import com.jnxx.task.vo.OKRRequestParamsVo;
import com.jnxx.task.vo.TextCardVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class SendToOKR {
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    public String sendMessage(Map<String, String> params, OKRRequestParamsVo okRRequestParamsVo, TextCardVo textCardVo){
        try {
            String accessToken = stringRedisTemplate.opsForValue().get("accessToken");
            if (accessToken == null){
                accessToken = tokenUtils.getAccessToken();
            }
            String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
            String descript = params.get("descript");
            String nowTime = GetStaffRequestUtil.getNowTime();
            // 设置时间
            String descriptin = String.format(descript, nowTime);
            textCardVo.setDescription(descriptin);
            Map<String, Object> sendMessageMap = new HashMap<>();
            sendMessageMap.put("touser", params.get("touser"));
            sendMessageMap.put("msgtype", okRRequestParamsVo.getMsgtype());
            sendMessageMap.put("agentid", okRRequestParamsVo.getAgentid());
            sendMessageMap.put("textcard",textCardVo);
            sendMessageMap.put("enable_id_trans", okRRequestParamsVo.getEnable_id_trans());
            sendMessageMap.put("enable_duplicate_check", okRRequestParamsVo.getEnable_duplicate_check());
            return restTemplate.postForObject(url, sendMessageMap, String.class);
        } catch (Exception e) {
            e.printStackTrace();
            return "请求失败";
        }
    }
}
